package com.kstech.exccheck.view.check;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kstech.exccheck.R;
import com.kstech.exccheck.communication.CommandSender;
import com.kstech.exccheck.config.ConfigFileManager;
import com.kstech.exccheck.db.CheckItemDao;
import com.kstech.exccheck.domain.check.CheckItemEntity;
import com.kstech.exccheck.domain.check.CheckRecordEntity;
import com.kstech.exccheck.domain.check.CheckTimer;

import com.kstech.exccheck.domain.check.SingleCheckReadyTask;
import com.kstech.exccheck.domain.check.SingleCheckTask;
import com.kstech.exccheck.receiver.RealTimeChangedListener;
import com.kstech.exccheck.receiver.SingleCheckRealTimeParamReceiver;
import com.kstech.exccheck.receiver.WifiService;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.util.DialogUtil;
import com.kstech.exccheck.view.BaseActivity;
import com.kstech.exccheck.view.upload.Globals;

import java.util.List;


/**
 * @author lijie
 * 单项检测界面
 */
public class SingleCheckActivity extends BaseActivity implements
        View.OnClickListener, IntentConstant{

    private TextView deviceNameTV, subdeviceNameTV, excIdTV;
    public Button singleCheckBeginCheckLeftBtn, singleCheckTimeBtn,
            singleCheckExitCheckBtn, singleCheckBeginCheckRightBtn;

    // 下一项目按钮，或，退出测量按钮，两者可见其一
    private Button singleCheckNextItemBtn;

    /**
     * 主动指令信息提示区
     */
    private TextView msgTv;
    /**
     * 被动接收信息提示区
     */
    private LinearLayout msgLayoutView;

    /**
     * The Check item entity.
     */
    public CheckItemEntity checkItemEntity;

    private SingleCheckReadyTask singleCheckReadyTask = new SingleCheckReadyTask(this);
    private SingleCheckTask singleCheckTask = new SingleCheckTask(this);

    private String excId;

    private CheckItemSingleView checkItemSingleView;

    // 实时参数表体
    private TableLayout singleRealTimeParamBody;
    private SingleCheckRealTimeParamReceiver receiver;

    // 检查项列表，用于，下一项目，使用
    private List<CheckItemEntity> checkItemList;

    // 主页面的按钮，单项检测或流程检测
    private String checkBtnName;
    private ServiceConnection serviceConnection;
    private WifiService wifiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_check);

        DialogUtil.showDialog(this,View.inflate(this, R.layout.dialog_layout, null));

        // 初始化菜单
        initMenu("---   单项检验");

        checkItemSingleView = new CheckItemSingleView(this);
        // 初始化页面组件
        initViewComp();

        initListener();

        Intent intent = this.getIntent();
        checkItemList =  ((CheckRecordEntity) intent.getSerializableExtra(CHECK_RECORD)).getCheckItemList();

        checkItemEntity = (CheckItemEntity) intent
                .getSerializableExtra(CHECK_ITEM);
        excId = intent.getStringExtra(EXC_ID);
        String deviceName = intent.getStringExtra(DEVICE_NAME);
        String subDeviceName = intent.getStringExtra(SUB_DEVICE_NAME);
        deviceNameTV.setText(deviceName);
        subdeviceNameTV.setText(subDeviceName);
        excIdTV.setText(excId);
        // 如果是单项检测，则 修改按钮名称为退出测量
        checkBtnName = intent.getStringExtra(DCHECK_BTN_NAME);
        if (checkBtnName.equals("single")){
            singleCheckNextItemBtn.setText("退出测量");
        }

        // 初始化 项目参数列表
        checkItemSingleView.initCheckItemParamList(checkItemEntity);

        // 注册广播接收器
        receiver = new SingleCheckRealTimeParamReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction(RealTimeChangedListener.class.getName());
        SingleCheckActivity.this.registerReceiver(receiver,filter);

        // 按照配置文件，初始化设备通道参数表格，可以理解为主参数所依赖的传感器
        receiver.initTable(singleRealTimeParamBody,checkItemEntity.getItemId(),msgLayoutView,this);

        // 进入到单项检测页面，则自动发送准备检测命令
        singleCheckReadyTask.start(checkItemEntity);
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                WifiService.MyBinder binder = (WifiService.MyBinder) service;
                wifiService = binder.getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        DialogUtil.dialog.cancel();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopWIFIListener();
        // 取消 receiver 注册
        SingleCheckActivity.this.unregisterReceiver(receiver);
        // 回传响应码
        setResult(2);
    }

    /**
     * Init view.
     */
    public void initViewComp() {
        deviceNameTV = (TextView) findViewById(R.id.deviceNameTV);
        subdeviceNameTV = (TextView) findViewById(R.id.subdeviceNameTV);
        excIdTV = (TextView) findViewById(R.id.excIdTV);
        checkItemSingleView.initView();

        singleCheckBeginCheckLeftBtn = (Button) findViewById(R.id.singleCheckBeginCheckLeftBtn);
        singleCheckNextItemBtn = (Button) findViewById(R.id.singleCheckNextItemBtn);
        singleCheckTimeBtn = (Button) findViewById(R.id.singleCheckTimeBtn);
        singleCheckExitCheckBtn = (Button) findViewById(R.id.singleCheckExitCheckBtn);
        singleCheckBeginCheckRightBtn = (Button) findViewById(R.id.singleCheckBeginCheckRightBtn);

        msgTv = (TextView) findViewById(R.id.msgTv);
        msgLayoutView = (LinearLayout) findViewById(R.id.msgLayoutView);

        singleRealTimeParamBody = (TableLayout) findViewById(R.id.singleRealTimeParamBody);
    }

    /**
     * 初始化按钮监听器
     */
    public void initListener() {
        singleCheckBeginCheckLeftBtn.setOnClickListener(this);
        singleCheckNextItemBtn.setOnClickListener(this);
//        singleCheckExitCheckBtn.setOnClickListener(this);
        singleCheckBeginCheckRightBtn.setOnClickListener(this);
    }

    /**
     * 计时器handle
     */
    private Handler timeHandler = new Handler();
    /**
     * 计时器
     */
    private CheckTimer checkTimer = new CheckTimer(this);

    /**
     * Gets handler.
     *
     * @return the handler
     */
    public Handler getHandler() {
        return timeHandler;
    }

    /**
     * Gets check timer.
     *
     * @return the check timer
     */
    public CheckTimer getCheckTimer() {
        return checkTimer;
    }

    /**
     * 任务状态
     */
    private String taskState = CheckTimer.STOP;
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.singleCheckBeginCheckLeftBtn:
                beginStopHandle();
                break;
            case R.id.singleCheckNextItemBtn:
                if (checkBtnName.equals("single")){
                    exitHandle();
                } else {
                    // 如果计时器是停止状态，则可以点击下一项目按钮，否则不可点击
                    if (taskState.equals(CheckTimer.STOP) || taskState.equals(CheckTimer.READY_FINISH)
                            || taskState.equals(CheckTimer.READY_ERROR)) {
                        // 求出下一项
                        for (int i=0;i<checkItemList.size();i++) {
                            if(checkItemList.get(i).getItemId().equals(checkItemEntity.getItemId())) {
                                // 如果当前项不是最后一项
                                if (i+1 < checkItemList.size()){
                                    checkItemEntity = checkItemList.get(i+1);
                                    // 初始化 项目参数列表
                                    checkItemSingleView.initCheckItemParamList(checkItemEntity);
                                    // 点击下一项后，重新初始化实时参数配置
                                    singleCheckTimeBtn.setText("00:00");
                                    receiver.viewMapclear();
                                    receiver.initTable(singleRealTimeParamBody,checkItemEntity.getItemId(),msgLayoutView,this);
                                    // 自动发送准备检测命令
                                    singleCheckReadyTask.start(checkItemEntity);
                                    // 保存最后一次点击的 itemID
                                    ConfigFileManager.getInstance().saveLastItemid(checkItemEntity.getItemId());
                                    break;
                                } else {
                                    new AlertDialog.Builder(this).setMessage(R.string.current_item_is_last_item).setNeutralButton(R.string.str_ok, null).show();
                                }
                            }
                        }
                    } else {
                        new AlertDialog.Builder(this).setMessage(R.string.please_wait_currentTask_over).setNeutralButton(R.string.str_ok, null).show();
                    }
                }
                break;
            case R.id.singleCheckBeginCheckRightBtn:
                beginStopHandle();
                break;
            default:
                break;
        }
    }

    /**
     * UI--handler
     */
    private Handler uiHandler = new Handler();

    /**
     * 检测过程中UI通知
     *
     * @param msg       the msg
     * @param taskState the task state
     */
    public void checkUINotice(final String msg,final String taskState){
        this.taskState = taskState;
        // 计时器需要在主线程中操作
        if (taskState.equals(CheckTimer.STOP) || taskState.equals(CheckTimer.READY_FINISH) || taskState.equals(CheckTimer.READY_ERROR) ) {
            stopWIFIListener();
            checkTimer.stop();
        } else if (taskState.equals(CheckTimer.START) || taskState.equals(CheckTimer.READY)) {
            checkTimer.start();
        }
        uiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // UI通知必须在handle子线程中操作
                if (taskState.equals(CheckTimer.STOP) || taskState.equals(CheckTimer.READY_ERROR) ) {
                    // 一旦执行一次检验后，需要更新 checkItemEntity 实体中的内容
                    checkItemEntity = CheckItemDao.getSingleCheckItemFromDB(excId, checkItemEntity.getItemId());
                    // 更新检查项的检验信息
                    checkItemSingleView.initCheckItemParamList(checkItemEntity);

                    singleCheckBeginCheckLeftBtn.setText(R.string.beginCheck);
                    singleCheckBeginCheckRightBtn.setText(R.string.beginCheck);
                } else if (taskState.equals(CheckTimer.START)) {
                    singleCheckBeginCheckLeftBtn.setText(R.string.stopCheck);
                    singleCheckBeginCheckRightBtn.setText(R.string.stopCheck);
                }
                // 信息面板显示信息
                msgTv.setText(msg);
            }
        }, 0);
    }

    /**
     * 开始测量，终止测量，处理
     */
    private void beginStopHandle(){
        if (taskState.equals(CheckTimer.STOP) || taskState.equals(CheckTimer.READY_FINISH)) {
            startwifilistener();
            // 开始检测
            singleCheckTask.start(checkItemEntity);
        } else if (taskState.equals(CheckTimer.START) || "".equals(taskState)){
            stopWIFIListener();
            // 人工终止测量
            singleCheckTask.stop();
        }else{
            Toast.makeText(this,"传感器异常，无法开始检测",Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 退出测量处理
     */
    private void exitHandle(){
        // 提示，确认退出测量吗？
        new AlertDialog.Builder(AppContext.context)
                .setTitle(R.string.diaLogWakeup)
                .setMessage(R.string.stopCheckConfirm)
                .setNegativeButton(R.string.str_close, null)
                .setPositiveButton(R.string.str_ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                stopWIFIListener();
                                Globals.isSingleChecking = false;
                                // 回传响应码
                                CommandSender.sendStopCheckCommand(checkItemEntity.getItemId(),checkItemEntity.getSumTimes());
                                setResult(2);
                                finish();
                            }
                        }).show();
    }

    /**
     * 准备检测UI通知
     *
     * @param msg       the msg
     * @param taskState the task state
     */
    public void checkUINoticeForReady(final String msg,final String taskState){
        this.taskState = taskState;
        // 计时器需要在主线程中操作
        if (taskState.equals(CheckTimer.STOP) || taskState.equals(CheckTimer.READY_FINISH) || taskState.equals(CheckTimer.READY_ERROR) ) {
            checkTimer.stop();
        } else if (taskState.equals(CheckTimer.START) || taskState.equals(CheckTimer.READY)) {
            checkTimer.start();
        }
        uiHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 信息面板显示信息
                msgTv.setText(msg);
            }
        }, 0);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(AppContext.context)
                .setTitle(R.string.diaLogWakeup)
                .setMessage(R.string.stopCheckConfirm)
                .setNegativeButton(R.string.str_close, null)
                .setPositiveButton(R.string.str_ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                finish();
                            }
                        }).show();
    }

    /**
     * Tuichu.
     *
     * @param view the view
     */
    public void tuichu(View view) {
        exitHandle();
    }

    /**
     * Startwifilistener.
     */
    public void startwifilistener() {
        Intent intent = new Intent(this, WifiService.class);
        startService(intent);
        bindService(intent, serviceConnection,BIND_AUTO_CREATE);
    }

    /**
     * Stop wifi listener.
     */
    public void stopWIFIListener(){
        Intent intent = new Intent(this, WifiService.class);
        stopService(intent);
        unbindService(serviceConnection);
    }
}
